/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, {useEffect, useState} from 'react';
import {StyleSheet, View, Dimensions, Image} from 'react-native';
import {Fold, useBreakpointValue, useHeightBreakpointValue} from '@hadss/react_native_adaptive_layout';
import type {ViewStyle, ImageSourcePropType} from 'react-native';
import Context from './Context';
import type {ModeType, CameraPosition} from './Context';
import {Options, ModeSetting, Action, Camera, Counter, Preview} from './widegts';
import Orientation from 'react-native-orientation-locker';



/**
 * @description 拍照录像页
 * @param navigation
 * @returns ReactNode
 */
const Pic = ({navigation}: any) => {
  const [modeIndex, setModeIndex] = useState(3);
  const [mode, setMode] = useState<ModeType>('photo');
  const [mediaType, setMediaType] = useState<ModeType>('photo');
  const [position, setPosition] = useState<CameraPosition>('back');
  const [isRecording, setIsRecording] = useState<boolean>(false);
  const [path, setPath] = useState<ImageSourcePropType>(
    require('../../../assets/pic/ic_camera_shoot_bar_photo_normal.png'),
  );
  const [isOpenVideo, setIsOpenVideo] = useState(false);
  const [isOpenPhoto, setIsOpenPhoto] = useState(true);
  const [isLandscape, setIsLandscape] = useState(false);
  const {width, height} = Dimensions.get('window');
  const handleDimensionsChange = ({window}) => {
    setIsLandscape(window.width > window.height);
  };
  const [zoom, setZoom] = useState(1);
  const subscription = Dimensions.addEventListener('change', handleDimensionsChange);

  /** 高度是否匹配小折叠或者小分屏 */
  const isSmall = useHeightBreakpointValue<boolean>({
    base: false,
    // 小分屏
    sm: true,
    // 小折叠
    md: true,
    lg: false,
  });

  const isMd = useBreakpointValue<boolean>({
    base: false,
    sm: false,
    md: true,
    lg: false,
  });

  const isSm = useBreakpointValue<boolean>({
    base: false,
    sm: true,
    md: false,
    lg: false,
  });
  console.log('isSmall: ', isSmall);
  useEffect(() => {
    if (isMd) {
      setPosition('back');
    }
    if (isSm) {
      Orientation.lockToPortrait();
    } else {
      Orientation.unlockAllOrientations();
    }
    subscription?.remove();
  }, [isSmall, mode, isMd, isSm]);
  const isLg = width > 1000;
  /** 容器动态内间距 */
  const padding = useBreakpointValue<ViewStyle>({
    base: {paddingTop: 36, paddingBottom: 28},
    sm: isSmall ? {paddingTop: 16, paddingBottom: 0} : {paddingTop: 36, paddingBottom: 0},
    md: {paddingTop: 0, paddingBottom: 0},
    lg: {paddingTop: 0, paddingBottom: 0},
  });
  console.log('isMd: ', isMd);
  console.log('isLg: ', isLg);
  console.log('width:', width);
  console.log('height: ', height);
  const cameraContainer = useBreakpointValue<ViewStyle>({
    base: {
      position: 'absolute',
      width: isOpenVideo ? height * (9 / 16) : height * (3 / 4),
      height: height,
      zIndex: 0,
      top: isSm ? 0 : isOpenVideo ? 76 : 16,
    },
    sm:
      isSm && width / height > 0.8 && width / height < 1.2 && Fold.getFoldStatus() === 'folded'
        ? {
            flex: 1,
            position: 'absolute',
            width: width,
            height: width,
            zIndex: 0,
            overflow: 'hidden',
          }
        : {
            position: 'absolute',
            width: isOpenVideo ? height * (9 / 16) : height * (3 / 4),
            height: height,
            zIndex: 0,
            top: isSm ? 0 : isOpenVideo ? 76 : 16,
          },
  });
  return (
    <Context.Provider
      value={{
        mode,
        setMode,
        position,
        setPosition,
        isRecording,
        setIsRecording,
        path,
        setPath,
        mediaType,
        setMediaType,
        isOpenVideo,
        setIsOpenVideo,
        isOpenPhoto,
        setIsOpenPhoto,
        zoom,
        setZoom,
      }}>
      <View style={[styles.container, {...padding}]}>
        {/* 背景层 - 相机 */}
        <View style={cameraContainer}>
          <Camera isOpenVideo={isOpenVideo} isOpenPhoto={isOpenPhoto} zoom={zoom} />
        </View>
        {isRecording && <Counter />}
        <Options
          onPress={() => {
            navigation.goBack();
          }}
        />
        <Wrapper width={width} isSmall={isSmall ?? false} modeIndex={modeIndex} setModeIndex={setModeIndex} />
      </View>
    </Context.Provider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
    backgroundColor: '#000',
    justifyContent: 'center', // 垂直居中
    alignItems: 'center', // 水平居中
    overflow: 'hidden',
  },
  cameraParent: {
    maxWidth: '100%',
    maxHeight: '100%',
  },
});

/**
 * @description 相机底部区域或右侧区域，需要根据屏幕端点进行设置
 * @param props
 * @returns
 */
const Wrapper = (props: {width: number; isSmall: boolean}) => {
  const render = useBreakpointValue({
    base: (
      <View
        style={{
          bottom: props.isSmall ? 8 : 82,
          width: '100%',
          position: 'absolute',
        }}>
        <ModeSetting />
        <Action />
      </View>
    ),
  });
  return <>{render}</>;
};

export default Pic;
